<?php

namespace App\Http\Services;

use App\Http\Model\FinanceDiamond;
use App\Http\Model\FinanceUserWallet;
use Exception;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\Hint;
use App\Http\Model\User;
use App\Http\Model\Gift;
use App\Http\Model\GiftBag;
use App\Http\Model\DefenderDraw;
use App\Http\Model\Mall;
use App\Http\Model\Room;
use App\Http\Model\RoomHot;
use App\Http\Model\System;
use App\Model\FinanceWallet;
use App\Modules\LuckDraw\Models\UserPropLogModel;
use App\Modules\LuckDraw\Models\UserPropModel;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class DefenderDrawServices extends CommonServices
{
    protected $userModel;
    protected $giftModel;
    protected $DefenderDrawModel;
    protected $customService;
    protected $giftBag_model;
    protected $systemModel;
    protected $msgService;
    protected $financeUserWallet;
    protected $FinanceDiamond;
    protected $userPropModel;
    protected $userPropLogModel;
    protected $mall_model;
    protected $DefenderId;
    protected $roomHotModel;
    protected $dayAwardPic = '/icon/universe_day_award.png';//日榜图片
    protected $weekAwardPic = '/icon/universe_week_award.png';//周榜图片

    protected $allUniverseValue = 'DEFENDER:VALUE';//全服擂主值
    protected $universeDefenderId = 'DEFENDER:DefenderID';//当前池子id
    protected $universeEndTime = 'DEFENDER:ENDTIME';//结束时间
    protected $dayStarRank = 'DEFENDER:DAY:RANK:';//日榜
    protected $weekStarRank = 'DEFENDER:WEEK:RANK:';//周榜

    public function __construct()
    {
        parent::__construct();

        $this->userModel = new User();
        $this->giftModel = new Gift();
        $this->DefenderDrawModel = new DefenderDraw();
        $this->customService = new CustomServices();
        $this->giftBag_model = new GiftBag();
        $this->systemModel = new System();
        $this->financeUserWallet = new FinanceUserWallet();
        $this->msgService = new MsgServices();
        $this->FinanceDiamond = new FinanceDiamond();
        $this->userPropModel = new UserPropModel();
        $this->userPropLogModel = new UserPropLogModel();
        $this->mall_model = new Mall();
        $this->roomHotModel = new RoomHot();
        $this->DefenderId = 1000;
    }

    /**
     * 擂主变全服中奖记录列表
     */
    public function awardListV2($page, $limit, $userId = '', $DefenderId = '')
    {
        $data = [];
        do {
            $where['Defender_id'] = $DefenderId;
            $list = $this->DefenderDrawModel->awardListV2($page, $limit, $where);

            $listEx = [];
            if (!empty($list)) {
                $userIds = array_column($list, 'user_id');
                $userList = $this->userModel->getUserInfoByIds($userIds);
                $userList = array_column($userList, null, 'user_id');

                $giftIds = array_column($list, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'image', 'price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach ($list as $key => $val) {
                    $newArr = [];
                    if (empty($userList[$val['user_id']])) {
                        continue;
                    }
                    if (empty($giftList[$val['gift_id']])) {
                        continue;
                    }
                    $newArr['userId'] = $val['user_id'];
                    $newArr['giftId'] = $val['gift_id'];
                    $newArr['name'] = $giftList[$val['gift_id']]['name'];
                    $newArr['price'] = $giftList[$val['gift_id']]['price'];
                    $newArr['num'] = $val['gift_num'];
                    $newArr['createdAt'] = $val['created_at'];
                    $newArr['nickname'] = $userList[$val['user_id']]['nickname'];
                    $newArr['uuid'] = $userList[$val['user_id']]['uuid'];
                    $newArr['avatar'] = build_image(json_decode($userList[$val['user_id']]['portrait'], true)[0]);
                    $newArr['image'] = build_image($giftList[$val['gift_id']]['image']);
                    $newArr['Defender_id'] = $val['pool_level'];

                    $listEx[] = $newArr;
                }
            }


            $data = $listEx;
        } while (false);

        return $data;
    }

    private function _getAperture($price)
    {
        $aperture = 0;
        if ($price >= 0 and $price < 100000) {
            $aperture = 1;
        } elseif ($price >= 100000 and $price < 300000) {
            $aperture = 2;
        } elseif ($price >= 300000) {
            $aperture = 3;
        } else {
            $aperture = 0;
        }
        return $aperture;
    }

    /**
     * 擂主变奖池配置剩余数量
     */
    public function DefenderDrawPoolConfigNum($poolId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            try {
                if (empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }
                $poolList = $this->DefenderDrawModel->getDefenderDrawPoolConfig($poolId);
                if (empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }

                $hasList = $this->DefenderDrawModel->getDefenderDrawPoolData($poolList['Defender_id'], $poolId);
                $hasList = array_column($hasList, 'num', 'id');

                $giftIds = array_column($poolList['pool'], 'id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach ($poolList['pool'] as $key => $val) {
                    $val['Defender_id'] = $poolList['Defender_id'];
                    $val['pool_id'] = $poolList['id'];
                    $val['gift_id'] = $val['id'];
                    $val['gift_num'] = $val['num'];
                    $val['gift_name'] = empty($giftList[$val['id']]['name']) ? '' : $giftList[$val['id']]['name'];
                    $val['gift_price'] = empty($giftList[$val['id']]['price']) ? 0 : $giftList[$val['id']]['price'];
                    $val['less_num'] = empty($hasList[$val['id']]) ? 0 : $hasList[$val['id']];
                    $val['draw_num'] = $val['num'] - $val['less_num'];

                    $data[] = $val;
                }
            } catch (\Exception $e) {
                $code = Hint::ERROR;
                $msg = '异常:' . $e->getMessage();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }


    /**
     * 擂主变池子外显概率列表
     */
    public function poolAwardListV2($DefenderId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($DefenderId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $list = $this->DefenderDrawModel->getWishDefenderGift($DefenderId);

            $listEx = [];
            if(!empty($list)) {
                $giftIds = array_column($list, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds,['gift_id','name','image','price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach($list as $key=>$val) {
                    if(empty($giftList[$val['gift_id']])) {
                        continue;
                    }
                    $item = [];
                    $item['gift_id'] = $val['gift_id'];
                    $item['name'] = $giftList[$val['gift_id']]['name'];
                    $item['price'] = $giftList[$val['gift_id']]['price'];
                    $item['image'] = build_image($giftList[$val['gift_id']]['image']);
                    $item['add_star'] = 0;
                    $startRate = $giftList[$val['gift_id']]['price']/100;
                    $item['add_star'] = number_format($startRate,2,'.','');
                    $listEx[] = $item;
                }
            }

            $data = $listEx;

            usort($data, function ($a, $b) {
                return $b['price'] <=> $a['price'];
            });
        } while (false);
        return compact('code', 'msg', 'data');
    }

    /**
     * 获取滚动记录
     */
    public function marquee($top)
    {
        $code = Hint::SUCCESS;
        $msg = 'OK';
        $data = [];
        do {
            $res = $this->DefenderDrawModel->marquee($top);
            if (empty($res)) {
                break;
            }
            $giftIds = array_column($res, 'gift_id');
            $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'image', 'price']);
            $giftList = array_column($giftList, null, 'gift_id');

            $userIds = array_column($res, 'user_id');
            $userList = $this->userModel->getUserInfoByIds($userIds);
            $userList = array_column($userList, null, 'user_id');
            foreach ($res as $k => $v) {
                $newArr = [
                    'type' => 1, //奖品类型 1、礼物 2、商品 
                    'DefenderId' => $v['pool_id'],
                    'userId' => $v['user_id'],
                    'awardId' => $v['id'],
                    'timeLimit' => 0,
                    'name' => $giftList[$v['gift_id']]['name'],
                    'image' => build_image($giftList[$v['gift_id']]['image']),
                    'price' => $giftList[$v['gift_id']]['price'],
                    'num' => $v['gift_num'],
                    'aperture' => $this->_getAperture($giftList[$v['gift_id']]['price']),
                    'nickname' => $userList[$v['user_id']]['nickname'],
                ];
                $data[] = $newArr;
            }
        } while (false);
        return compact('code', 'data', 'msg');
    }

    /**
     * 抽奖
     */
    public function wishPoolDraw($userId, $num, $roomId, $DefenderId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $DefenderId = $DefenderId;
        $now = time();
        do {
            //获取目前奖池
            $progressInfo = $this->getProgess();
            if($DefenderId != $progressInfo['Defender_id']){
                $code = Hint::UNIVERSE_CHANGE_ERROR;
                $data = $progressInfo;
                break;
            }
            $num = abs($num);
            //配置
            $config = $this->DefenderDrawModel->getWishPoolConfig();
            if (empty($config)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            if($DefenderId == 1000){
                $oneNum = $config['need_num'];
            }else{
                $oneNum = 3*$config['need_num'];
            }
            $needNum = $oneNum * $num;

            //个人池用户
            $poolUser = $this->DefenderDrawModel->getWishDefenderPoolUserId($userId, $DefenderId);

            //获取用户当前抽奖的奖池
            //奖池
            $pool = $this->DefenderDrawModel->getWishDefenderPool($DefenderId);
            $basePoolList = []; //普通池的
            $userPoolList = []; //用户个人池的
            foreach ($pool as $val) {
                if ($val['status'] != 1) {
                    continue;
                }
                //奖池配置数据
                $poolConfig = $this->DefenderDrawModel->getWishDefenderPoolConfig($val['id']);
                if (empty($poolConfig)) {
                    continue;
                }
                $val['poolConfig'] = $poolConfig;
                //普通池
                if ($val['pool_type'] == 1) {
                    $basePoolList[] = $val;
                }
                //用户个人池
                if (in_array($val['pool_type'], [2, 3])) {
                    if (!empty($poolUser) && !empty($poolUser['pool_id']) && $val['id'] == $poolUser['pool_id']) {
                        $userPoolList[] = $val;
                    }
                }
            }

            $poolList = []; //已开启的奖池
            $giftToItemNo = []; //奖池礼物对应的奖池序号
            $ifdrawInUserPool = 0; //是否在个人池抽奖 0=否 1=是
            if (!empty($poolUser) && !empty($userPoolList)) {
                $poolList = $userPoolList;
                $ifdrawInUserPool = 1;
            } else {
                $poolList = $basePoolList;
            }
            if (empty($poolList)) {
                $code = Hint::WAIT_OPEN;
                break;
            }
            $giftToItemNo = array_column($poolList[0]['poolConfig'], 'item_no', 'gift_id');

            //恋爱卡价格
            $DefenderDrawInfo = $this->DefenderDrawModel->DefenderDrawInfo(1000);
            $DefenderDrawPrice = empty($DefenderDrawInfo['price']) ? 0 : $DefenderDrawInfo['price'];

            //用户恋爱卡数量
            $userDefenderDrawProp = $this->DefenderDrawModel->getAvail(1000, $userId);
            if ($userDefenderDrawProp < $needNum) {
                $code = Hint::Defender_DRAW_PROP_NOT_ENOUGH;
                $msg = '告白币数量不足';
                break;
            }

            //扣恋爱卡
            $decrRes = $this->DefenderDrawModel->decrUniverseTickerUserProp($userId, 1000, $needNum);
            if (!$decrRes) {
                $code = Hint::Defender_DRAW_PROP_NOT_ENOUGH;
                $msg = '告白币数量不足';
                break;
            }

            //人气票发放
            $this->customService->SendTicket($userId, $needNum, $DefenderDrawPrice, 7);

            //用户信息
            $userInfo = $this->userModel->get_users_by_ids([$userId]);
            $userInfo = array_column($userInfo, null, 'user_id');
            $userInfo = $userInfo[$userId];

            //用户总抽奖记录数
            if ($ifdrawInUserPool) {
                //个人池用户
                $drawNumNow = $drawNum = $poolUser['draw_num'];
            } else {
                //普通
                $drawNumNow = $drawNum = $this->DefenderDrawModel->getUserWishDefenderDrawNumByWeek($userId, $DefenderId);
            }

            //白名单
            $whiteListNow = $whiteList = $this->DefenderDrawModel->getWishDefenderWhite($userId, $DefenderId);
            //订单记录
            $orderInfo = [
                'user_id' => $userId,
                'num' => $num,
                'prop_num' => $needNum,
                'prop_diamond_num' => $needNum * $DefenderDrawPrice,
                'reward_diamond_num' => 0,
                'pool_level' => $DefenderId,
                'created_at' => date('Y-m-d H:i:s', $now),
            ];
            $orderId = $this->DefenderDrawModel->addWishDefenderOrder($orderInfo);
            if (empty($orderId)) {
                $code = Hint::ERR_SYS_FAIL;
                break;
            }

            //抽奖
            $drawLogList = [];
            try {
                for ($i = 1; $i <= $num; $i++) {
                    $drawNumNow = $drawNumNow + 1;
                    $drawLog = [];
                    $drawLog['draw_no'] = $i;
                    $drawLog['gift_id'] = 0;
                    $drawLog['white_id'] = 0;
                    $drawLog['pool_id'] = 0;
                    $drawLog['item_no'] = 0;
                    //白名单
                    if (!empty($whiteListNow)) {
                        $whiteInfo = array_shift($whiteListNow);
                        $drawLog['gift_id'] = $whiteInfo['gift_id'];
                        $drawLog['white_id'] = $whiteInfo['id'];
                        $drawLog['item_no'] = empty($giftToItemNo[$whiteInfo['gift_id']]) ? 11 : $giftToItemNo[$whiteInfo['gift_id']];
                    } else {
                        $usePool = []; //使用的奖池
                        //在范围的
                        foreach ($poolList as $val) {
                            if ($val['min_num'] <= $drawNumNow && $drawNumNow <= $val['max_num']) {
                                $usePool = $val;
                            }
                        }
                        //上一个
                        $prevNum = 0;
                        if (empty($usePool)) {
                            foreach ($poolList as $val) {
                                if ($val['max_num'] <= $drawNumNow && $prevNum <= $val['max_num']) {
                                    $usePool = $val;
                                    $prevNum = $val['max_num'];
                                }
                            }
                        }
                        //下一个
                        $nextNum = 0;
                        if (empty($usePool)) {
                            foreach ($poolList as $val) {
                                if ($val['min_num'] >= $drawNumNow && ($nextNum == 0 || $nextNum >= $val['min_num'])) {
                                    $usePool = $val;
                                    $nextNum = $val['min_num'];
                                }
                            }
                        }
                        //还是没有取第一个
                        if (empty($usePool)) {
                            $usePool = $poolList[0];
                        }

                        //抽取 
                        if (in_array($usePool['pool_type'], [2, 3])) {
                            //个人池
                            $poolConfigId = $this->DefenderDrawModel->drawWishDefenderUser($DefenderId, $usePool['id'], $userId);
                        } else {
                            //普通
                            $poolConfigId = $this->DefenderDrawModel->drawWishDefender($DefenderId, $usePool['id']);
                        }
                        $poolConfigMap = array_column($usePool['poolConfig'], null, 'id');

                        $drawLog['gift_id'] = $poolConfigMap[$poolConfigId]['gift_id'];
                        $drawLog['white_id'] = 0;
                        $drawLog['pool_id'] = $poolConfigMap[$poolConfigId]['pool_id'];
                        $drawLog['item_no'] = $poolConfigMap[$poolConfigId]['item_no'];
                    }

                    $drawLogList[] = $drawLog;
                }
            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                write_log('error_wishDefender', 'wishDefenderDraw 抽奖失败', ['orderId' => $orderId, 'message' => $e->getMessage(), 'line' => $e->getLine()]);
                break;
            }

            //累加用户总抽奖记录数
            $this->DefenderDrawModel->incrUserDrawWeekNum($userId, $num, $DefenderId);

            $giftIds = array_column($drawLogList, 'gift_id');
            $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price', 'image']);
            $giftList = array_column($giftList, null, 'gift_id');

            //抽奖保存
            DB::beginTransaction();
            try {
                $rewardDiamondNumAll = 0;
                //新增擂主变抽奖记录
                foreach ($drawLogList as $key => $val) {
                    $val['order_id'] = $orderId;
                    $val['user_id'] = $userId;
                    $val['prop_num'] = $config['need_num'];
                    $val['gift_num'] = 1;
                    $val['prop_diamond_num'] = $val['prop_num'] * $DefenderDrawPrice;
                    $val['reward_diamond_num'] = empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price'];
                    $val['created_at'] = date('Y-m-d H:i:s', $now);
                    $val['pool_level'] = $DefenderId;
                    $this->DefenderDrawModel->addWishDefenderDraw($val);

                    //奖励价值钻石数
                    $rewardDiamondNumAll = $rewardDiamondNumAll + $val['reward_diamond_num'];

                    //白名单
                    if (!empty($val['white_id'])) {
                        $this->DefenderDrawModel->updateWishDefenderWhite($val['white_id'], $orderId);
                    }

                    //送礼物
                    $this->giftBag_model->inc((int)$userId, 0, (int)$val['gift_id'], 1, 1000);

                    $drawLogList[$key] = $val;
                }
                //更新订单
                $this->DefenderDrawModel->updateWishDefenderDraw($orderId, $rewardDiamondNumAll);
                //更新个人池用户记录
                if ($ifdrawInUserPool && $val['white_id'] == 0) {
                    $this->DefenderDrawModel->updateWishDefenderUserPoolLog($poolUser['id'], $orderInfo['prop_diamond_num'], $rewardDiamondNumAll, $orderInfo['num']);
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_wishDefender', 'wishDefenderDraw 抽奖保存', ['orderId' => $orderId, 'drawLogList' => $drawLogList, 'message' => $e->getMessage(), 'line' => $e->getLine()]);
                break;
            }
            //更新擂主变用户每日抽奖数据统计缓存
            $this->DefenderDrawModel->updateWishDefenderUserDay($DefenderId, $userId, $orderInfo['prop_diamond_num'], $rewardDiamondNumAll, $orderInfo['num']);
            //更新全服擂主值
            $straValue = $rewardDiamondNumAll;
            $nowStart = Redis::get($this->allUniverseValue);
            $nowDefenderId = empty(Redis::get($this->universeDefenderId)) ? 1000 : Redis::get($this->universeDefenderId);
            if($nowStart >= $config['changePoolLimit'] && $nowDefenderId != 1001){
                //通告全服已开启高级奖池
                $now = Carbon::now()->timestamp;
                $now = date('Y-m-d H:i',$now);

                $endTime = strtotime($now) + $config['openMinutes'] * 60;
                Redis::set($this->universeDefenderId,1001);
                Redis::set($this->universeEndTime, date('Y-m-d H:i:s',$endTime));

                //发送飘屏/公屏公告
                $this->sendOpenPoolMsg($roomId);
            }else{
                //高级池2倍擂主值,不加全服擂主,只加个人擂主值
                if($nowDefenderId == 1001){
                    $straValue = 2*$straValue;
                }

                if($DefenderId == 1000){
                    Redis::INCRBYFLOAT($this->allUniverseValue, $straValue/100);
                }

                //记录数据库
                $insertData = [
                    'user_id'=>$userId,
                    'pool_level' => $DefenderId,
                    'add_star_value' => $straValue,
                    'reward_diamond' =>  $rewardDiamondNumAll,
                    'order_id' => $orderId,
                    'created_at' => date('Y-m-d H:i:s',time()),
                ];
                //增加用户日榜.周榜擂主值
                $todayStart = Carbon::today()->startOfDay()->toDateString();
                $dayKey = $this->dayStarRank.$todayStart;
                Redis::ZINCRBY($dayKey,$straValue, $userId);
                Redis::EXPIRE($dayKey, 7*86400);

                $weekStart = Carbon::today()->startOfWeek()->toDateString();
                $weekEnd = Carbon::today()->endOfWeek()->toDateString();
                $weekKey = $this->weekStarRank.$weekStart.'-'.$weekEnd;
                Redis::ZINCRBY($weekKey,$straValue, $userId);
                Redis::EXPIRE($weekKey, 7*86400);
                $this->DefenderDrawModel->insertStarValueLog($insertData);
            }

            //汇总返回值
            $resList = [];
            $frontList = [];
            $resList = $this->DefenderDrawModel->getDrawList($orderId);
            $giftType = 1;
            foreach ($resList as $k=>$vals) {
                $item = [];
                if($val['pool_level'] == 1001){
                    $giftType = 2;
                }
                $item['type'] = $giftType;
                $item['DefenderId'] = $val['pool_level'];
                $item['userId'] = $userId;
                $item['awardId'] = $orderId;
                $item['timeLimit'] = 0;
                $item['name'] = empty($giftList[$vals['gift_id']]['name']) ? '' : $giftList[$vals['gift_id']]['name'];
                $item['price'] = (int) (empty($giftList[$vals['gift_id']]['price']) ? 0 : $giftList[$vals['gift_id']]['price']);
                $item['image'] = empty($giftList[$vals['gift_id']]['image']) ? '' : build_image($giftList[$vals['gift_id']]['image']);
                $item['nickname'] = $userInfo['nickname'];
                $item['num'] = $vals['gift_num'];
                $add_star = number_format($item['price']*$item['num']/100,2,'.','');
                $item['add_star'] = $add_star;
                $resList[$k] = $item;
            }
            $resList = array_values($resList);
            array_multisort(array_column($resList, 'price'), SORT_DESC, $resList);

            //房间内游戏公屏游戏消息
            if ($roomId > 10) {
                //查询飘屏中设置的飘屏限制钻石数,因为公屏限制和飘屏限制一致
                if($DefenderId == 1000){
                    $fullScreen = $this->systemModel->getFullScreen(68);
                    //  $laceName = '宇宙擂主变(普通)';
                    $laceName = 'CC万神殿(一阶段)';
                }elseif($DefenderId == 1001) {
                    $fullScreen = $this->systemModel->getFullScreen(69);
                    $laceName = 'CC万神殿(二阶段)';

                }elseif($DefenderId == 1002) {
                    $fullScreen = $this->systemModel->getFullScreen(69);
                    $laceName = 'CC万神殿(三阶段)';

                }elseif($DefenderId == 1003) {
                    $fullScreen = $this->systemModel->getFullScreen(69);
                    $laceName = 'CC万神殿(四阶段)';

                }
                if (empty($fullScreen)) {
                    return false;
                }
                foreach ($resList as $val) {
                    if($val['price'] >= $fullScreen['special_full_screen_diamond']) {
//                        write_log('sendFullScreen', '发送世界消息:liya'.$fullScreen['special_full_screen_diamond'], $val['price']);
                        $this->msgService->roomWishPoolMsg2($roomId,['nickname' => $userInfo['nickname'], 'user_id' => $userInfo['user_id'], 'placeName' => $laceName, 'giftName' => $val['name'], 'giftPrice' => $val['price'], 'giftNum' => $val['num']]);
                    }
                    if($val['price']>180){
                        $this->msgService->roomWishPoolMsg($roomId, ['nickname' => $userInfo['nickname'], 'user_id' => $userInfo['user_id'], 'placeName' => $laceName, 'giftName' => $val['name'], 'giftPrice' => $val['price'], 'giftNum' => $val['num']]);
                    }
                }
            }

            $data['list'] = $resList;
            $data['order_id'] = $orderId;
            $data['reward_diamond_num'] = $rewardDiamondNumAll;
        } while (false);

        return compact('code', 'msg', 'data');
    }

    //礼物获取角标
    public function giftGetBanner($giftId)
    {

        return build_image('/icon/giftDefender.png');
    }

    /**
     * 飘屏处理
     */
    public function wishDefenderDrawFull($orderId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $DefenderId = 1000;
        $now = time();
        do {
            if (empty($orderId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $orderInfo = $this->DefenderDrawModel->orderAwardList($orderId);
            if (empty($orderInfo)) {
                break;
            }
            //配置
            $config = $this->DefenderDrawModel->getWishPoolConfig();
            if (empty($config)) {
                $code = Hint::PARAM_ERROR;
                break;
            }

            //告白币价格
            $DefenderDrawInfo = $this->DefenderDrawModel->DefenderDrawInfo($DefenderId);
            $DefenderDrawPrice = empty($DefenderDrawInfo['price']) ? 0 : $DefenderDrawInfo['price'];

            //用户信息
            $userInfo = $this->userModel->get_users_by_ids([$orderInfo['user_id']]);
            $userInfo = array_column($userInfo, null, 'user_id');
            $userInfo = $userInfo[$orderInfo['user_id']];

            $giftIds = array_column($orderInfo['drawList'], 'gift_id');
            $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price', 'image']);
            $giftList = array_column($giftList, null, 'gift_id');
            $sendUniverse = [];
            //飘屏
            foreach ($orderInfo['drawList'] as $val) {
                $giftPrice = empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price'];
                $giftName = empty($giftList[$val['gift_id']]['name']) ? 0 : $giftList[$val['gift_id']]['name'];
                //滚动公告
                //增加值
                $addStart =  number_format($val['reward_diamond_num']/100,2,'.','');
                $sendUniverse[] = [
                    'add_star' => $addStart,
                    'user_name' => $userInfo['nickname'],
                    'user_head' => $userInfo['images'][0],
                    'gift_name' => $giftName,
                    'gift_num' => $val['gift_num']
                ];
                //普通池/高级池不同飘屏
                if($val['pool_level'] == 1000){
                    $this->msgService->sendFullScreen(68, null, ['userName' => $userInfo['nickname'], 'diamondNum' => $giftPrice, 'giftName' => $giftName, 'giftNum' => $val['gift_num']], [], ['giftPrice' => $giftPrice]);
                }elseif($val['pool_level'] == 1001){
                    $this->msgService->sendFullScreen(69, null, ['userName' => $userInfo['nickname'], 'diamondNum' => $giftPrice, 'giftName' => $giftName, 'giftNum' => $val['gift_num']], [], ['giftPrice' => $giftPrice]);
                }
            }
            $nowStart = Redis::get($this->allUniverseValue);
            $nowDefenderId = empty(Redis::get($this->universeDefenderId)) ? 1000 : Redis::get($this->universeDefenderId);
            if($nowStart >= $config['changePoolLimit'] && $nowDefenderId != 1001){
                //通告全服已开启高级奖池
                $now = Carbon::now()->timestamp;
                $now = date('Y-m-d H:i',$now);

                $endTime = strtotime($now) + $config['openMinutes'] * 60;
                Redis::set($this->universeDefenderId,1001);
                Redis::set($this->universeEndTime, date('Y-m-d H:i:s',$endTime));

                //发送飘屏/公屏公告
                $this->sendOpenPoolMsg();
            }
            //发送公告
            $progressInfo = $this->getProgess();
            $this->msgService->sendUniverse($sendUniverse, $progressInfo['progress'], $progressInfo['Defender_id'], $progressInfo['leaveMinutes']);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 获取活动规则
     */
    public function getRule()
    {
        $config = $this->DefenderDrawModel->getWishPoolConfig();
        if (empty($config)) {
            return [];
        }
        $data = [];
        $data['play_rule'] = $config['rule'];
        $data['rank_rule'] = $config['rank_rule'];
        return $data;
    }

    /**
     * 兑换 波波币
     */
    public function exchange($num, $userId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $DefenderId = 1000;
        do {
            //获取所需钻石总额
            $DefenderDrawInfo = $this->DefenderDrawModel->DefenderDrawInfo($DefenderId);
            $DefenderDrawPrice = empty($DefenderDrawInfo['price']) ? 0 : $DefenderDrawInfo['price'];
            $needTotalDiamond = $DefenderDrawPrice * $num;
            //查询当前用户可用钻石
            $walletData = $this->financeUserWallet->get_wallet($userId);
            if ($walletData['diamond_balance'] < $needTotalDiamond) {
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }
            DB::beginTransaction();
            try {
                //扣除钻石
                $this->FinanceDiamond->inc($userId, 0, 0, 6, -$needTotalDiamond, '兑换告白币');
                //增加道具
                $ok = $this->userPropModel->add($DefenderId, $userId, $num);
                //道具保存成功则增加日志
                if ($ok) {
                    $ok = $this->userPropLogModel->log($DefenderId, $userId, 1000, $num);
                }
                //赠送头像框
                $goodId = 116;
                $goodInfo = $this->mall_model->getMallGoodByGoodsId($goodId);
                if (empty($goodInfo)) {
                    $code = Hint::DIAMOND_NOT_ENOUGH;
                    break;
                }
                $skuList = $this->mall_model->getSkuDataByGoods($goodId);
                if (empty($skuList[0])) {
                    $code = Hint::DIAMOND_NOT_ENOUGH;
                    break;
                }
                $goodMap[$goodId]['goods_name'] = $goodInfo['goods_name'];
                $goodMap[$goodId]['goods_type'] = $goodInfo['goods_type'];
                $goodMap[$goodId]['sku_id'] = $skuList[0]['sku_id'];
                //有效期
                $timeLimit = $num * 3600;
                //商品增加
                $this->mall_model->shoppingAct(
                    11,
                    $userId,
                    $goodId,
                    $goodMap[$goodId]['goods_name'],
                    $goodMap[$goodId]['goods_type'],
                    $goodMap[$goodId]['sku_id'],
                    $timeLimit,
                    0,
                    $timeLimit,
                    time(),
                    2
                );
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_wishDefender', 'error 兑换波波币', ['msg' => $e->getMessage(), 'line' => $e->getLine()]);
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }
            $walletData = $this->financeUserWallet->get_wallet($userId);
            $diamonNum = $walletData['diamond_balance'];
            $propNum = $this->userPropModel->getAvail($DefenderId, $userId);
            $data = [
                'diamond' => $diamonNum,
                'prop' => $propNum
            ];
        } while (false);
        return compact('code', 'data', 'msg');
    }

    /**
     * 兑换恋爱卡
     */
    public function universe_exchange($num, $userId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        $DefenderId = 1000;
        do {
            //获取所需钻石总额
            $DefenderDrawInfo = $this->DefenderDrawModel->DefenderDrawInfo($DefenderId);
            $DefenderDrawPrice = empty($DefenderDrawInfo['price']) ? 20 : $DefenderDrawInfo['price'];
            $needTotalDiamond = $DefenderDrawPrice * $num;
            //查询当前用户可用钻石
            $walletData = $this->financeUserWallet->get_wallet($userId);
            if ($walletData['diamond_balance'] < $needTotalDiamond) {
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }
            DB::beginTransaction();
            try {
                //扣除钻石
                $this->FinanceDiamond->inc($userId, 0, 0, 6, -$needTotalDiamond, '兑换恋爱卡');
                //增加道具
                $ok = $this->DefenderDrawModel->addTiket($DefenderId, $userId, $num);
                //道具保存成功则增加日志
                if ($ok) {
                    $ok = $this->DefenderDrawModel->addTiketLog($DefenderId, $userId, 1000, $num);
                }
                //赠送头像框
                $goodId = 120;
                $goodInfo = $this->mall_model->getMallGoodByGoodsId($goodId);
                if (empty($goodInfo)) {
                    $code = Hint::DIAMOND_NOT_ENOUGH;
                    break;
                }
                $skuList = $this->mall_model->getSkuDataByGoods($goodId);
                if (empty($skuList[0])) {
                    $code = Hint::DIAMOND_NOT_ENOUGH;
                    break;
                }
                $goodMap[$goodId]['goods_name'] = $goodInfo['goods_name'];
                $goodMap[$goodId]['goods_type'] = $goodInfo['goods_type'];
                $goodMap[$goodId]['sku_id'] = $skuList[0]['sku_id'];
                //有效期
                $timeLimit = $num * 3600;
                //商品增加
                $this->mall_model->shoppingAct(
                    11,
                    $userId,
                    $goodId,
                    $goodMap[$goodId]['goods_name'],
                    $goodMap[$goodId]['goods_type'],
                    $goodMap[$goodId]['sku_id'],
                    $timeLimit,
                    0,
                    $timeLimit,
                    time(),
                    2
                );
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_wishDefender', 'error 兑换恋爱卡', ['msg' => $e->getMessage(), 'line' => $e->getLine()]);
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }
            $walletData = $this->financeUserWallet->get_wallet($userId);
            $diamonNum = $walletData['diamond_balance'];
            $propNum = $this->DefenderDrawModel->getAvail($DefenderId, $userId);
            $data = [
                'diamond' => $diamonNum,
                'prop' => $propNum
            ];
        } while (false);
        return compact('code', 'data', 'msg');
    }

    /**
     * 获取资产信息
     */
    public function balance($userId)
    {
        $DefenderId = 1000;
        $used = $this->DefenderDrawModel->getUsed($userId, $DefenderId);
        $propNum = $this->userPropModel->getAvail($DefenderId, $userId);
        $data = [
            'prop' => $propNum,
            'exp' => $used,
        ];
        return $data;
    }

    /**
     * 获取资产信息
     */
    public function universeBalance($userId)
    {
        $DefenderId = 1000;
        $propNum = $this->DefenderDrawModel->getAvail($DefenderId, $userId);
        //用户擂主值
        $starValue = $this->DefenderDrawModel->getStarValueByUser($userId);
        $data = [
            'prop' => $propNum,
            'starValue' => (string)number_format($starValue/100, 2 , '.', '')
        ];
        return $data;
    }

    /**
     * 获取用户抽奖记录
     */
    public function wishDefenderAwardListByUserId($page, $limit, $userId)
    {
        $data = [];
        do {
            $where = [];
            //今天
            $where['user_id'] = $userId;
            $list = $this->DefenderDrawModel->wishDefenderAllAwardList($page, $limit, $where);
            $listEx = [];
            if (!empty($list)) {
                $userIds = array_column($list, 'user_id');
                $userList = $this->userModel->get_users_by_ids($userIds);
                $userList = array_column($userList, null, 'user_id');

                $giftIds = array_column($list, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'image', 'price']);
                $giftList = array_column($giftList, null, 'gift_id');
                $newArr = [];
                foreach ($list as $key => $val) {
                    if (empty($userList[$val['user_id']])) {
                        continue;
                    }
                    if (empty($giftList[$val['gift_id']])) {
                        continue;
                    }
                    $newArr['userId'] = $val['user_id'];
                    $newArr['giftId'] = $val['gift_id'];
                    $newArr['name'] = $giftList[$val['gift_id']]['name'];
                    $newArr['price'] = $giftList[$val['gift_id']]['price'];
                    $newArr['num'] = $val['gift_num'];
                    $newArr['createdAt'] = $val['created_at'];
                    $newArr['nickname'] = $userList[$val['user_id']]['nickname'];
                    $newArr['uuid'] = $userList[$val['user_id']]['user_uid'];
                    $newArr['avatar'] = build_image($userList[$val['user_id']]['images'][0]);
                    $newArr['image'] = build_image($giftList[$val['gift_id']]['image']);
                    $newArr['Defender_id'] = $val['pool_level'];
                    $listEx[] = $newArr;
                }
            }
            $data = $listEx;
            unset($listEx);
        } while (false);

        return $data;
    }

    /**
     * 获取单次抽奖价格
     */
    public function getPrice($DefenderId)
    {
        $DefenderDrawInfo = $this->DefenderDrawModel->DefenderDrawInfo($DefenderId);
        $DefenderDrawPrice = empty($DefenderDrawInfo['price']) ? 0 : $DefenderDrawInfo['price'];
        return ['price' => $DefenderDrawPrice];
    }

    /**后台配置 */

    /**
     * 编辑擂主变配置
     */
    public function editWishDefenderConfig($upData = [])
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($upData)) {
                break;
            }
            $res = $this->DefenderDrawModel->editWishDefenderConfig($upData);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主变设置奖池开启/关闭
     */
    public function wishDefenderSetPoolStatus($poolId, $poolStatus)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($poolId) || empty($poolStatus)) {
                break;
            }
            //配置
            $config = $this->DefenderDrawModel->getWishPoolConfig();
            if (empty($config)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $poolInfo = $this->DefenderDrawModel->getWishDefenderPoolById($poolId);
            //奖池
            $pool = $this->DefenderDrawModel->getWishDefenderPool($poolInfo['pool_level']);
            if (empty($pool[$poolId])) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $poolInfo = $pool[$poolId];
            $poolStatus = ($poolStatus == 1) ? 1 : 2;
            //开启
            if ($poolStatus == 1) {
                //区间内的奖池必须关闭
                $flag = 0;
                $openPool = []; //已开启的奖池
                foreach ($pool as $val) {
                    if ($val['status'] != 1) {
                        continue;
                    }
                    $openPool = $val;
                    //个人池不校验次数区间
                    if (in_array($val['pool_type'], [2, 3]) || in_array($poolInfo['pool_type'], [2, 3])) {
                        continue;
                    }
                    //校验次数区间
                    if ($val['pool_type'] == $poolInfo['pool_type']) {
                        if ($val['min_num'] <= $poolInfo['min_num'] && $poolInfo['min_num'] <= $val['max_num']) {
                            $code = Hint::PARAM_ERROR;
                            $msg = 'ERROR 1:与现有生效奖池' . $val['pool_name'] . '（' . $val['id'] . '）次数区间重合，请重新配置:';
                            $flag = 1;
                            break;
                        }
                        if ($val['min_num'] <= $poolInfo['max_num'] && $poolInfo['max_num'] <= $val['max_num']) {
                            $code = Hint::PARAM_ERROR;
                            $msg = 'ERROR 2:与现有生效奖池' . $val['pool_name'] . '（' . $val['id'] . '）次数区间重合，请重新配置:';
                            $flag = 1;
                            break;
                        }
                        if ($poolInfo['min_num'] <= $val['min_num'] && $val['min_num'] <= $poolInfo['max_num']) {
                            $code = Hint::PARAM_ERROR;
                            $msg = 'ERROR 3:与现有生效奖池' . $val['pool_name'] . '（' . $val['id'] . '）次数区间重合，请重新配置:';
                            $flag = 1;
                            break;
                        }
                        if ($poolInfo['min_num'] <= $val['max_num'] && $val['max_num'] <= $poolInfo['max_num']) {
                            $code = Hint::PARAM_ERROR;
                            $msg = 'ERROR 4:与现有生效奖池' . $val['pool_name'] . '（' . $val['id'] . '）次数区间重合，请重新配置:';
                            $flag = 1;
                            break;
                        }
                    }
                }
                if ($flag == 1) {
                    break;
                }

                //奖池配置数据是否有效
                $poolList = $this->DefenderDrawModel->getWishDefenderPoolConfig($poolId);
                if (empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '获取奖池配置失败';
                    break;
                }
                $flag = 0;
                $giftNumAll = 0;
                $inDiamondNum = 0; //总消耗钻石数
                $outDiamondNum = 0; //总产出钻石数
                foreach ($poolList as $val) {
                    if (empty($val['gift_id'])) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '奖池配置 序号' . $val['item_no'] . '未配置礼物';
                        $flag = 1;
                        break;
                    }
                    $giftNumAll = $giftNumAll + $val['gift_num'];

                    $giftInfo = $this->giftModel->getGift(['gift_id' => $val['gift_id']], ['gift_id', 'name', 'image', 'price']);
                    $outDiamondNum = $outDiamondNum + ($giftInfo['price'] * $val['gift_num']);
                    $inDiamondNum = $inDiamondNum + (200 * $config['need_num'] * $val['gift_num']);
//                    if($poolInfo['pool_level'] == 1001){
//                        $inDiamondNum = $inDiamondNum + (60 * $config['need_num'] * $val['gift_num']);
//                    }
                }
                if ($giftNumAll < 1) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '奖池配置 礼物数量总和不足1';
                    $flag = 1;
                    break;
                }
                // 奖池的爆出/消耗钻石数小于等于115%才可开启成功
//                $rate = round($outDiamondNum / $inDiamondNum, 2);
//                if ($rate > 1.5) {
//                    $code = Hint::PARAM_ERROR;
//                    $msg = '奖池配置 奖池的爆出:' . $outDiamondNum . ' /消耗钻石数:' . $inDiamondNum . ' 小于等于115%才可开启成功';
//                    $flag = 1;
//                    break;
//                }
                if ($flag == 1) {
                    break;
                }

                //和已开启的奖池比较是否礼物一致
                if (!empty($openPool)) {
                    $openPoolList = $this->DefenderDrawModel->getWishDefenderPoolConfig($openPool['id']);
                    if (empty($openPoolList)) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '已开启奖池配置异常';
                        break;
                    }
                    $openPoolGift = array_column($openPoolList, 'gift_id', 'item_no');
                    $poolGift = array_column($poolList, 'gift_id', 'item_no');
                    foreach ($openPoolGift as $k => $v) {
                        if ($poolGift[$k] != $v) {
                            $code = Hint::PARAM_ERROR;
                            $msg = '奖池配置 礼物ID与已开启奖池不一致,奖池序号:' . $k;
                            $flag = 1;
                            break;
                        }
                    }
                    if ($flag == 1) {
                        break;
                    }
                }
                //重制奖池
                $res = $this->wishWheelDefenderReset($poolId);
                if ($res['code'] != Hint::SUCCESS) {
                    return $res;
                }
            }

            $res = $this->DefenderDrawModel->editWishDefenderPool($poolId, ['status' => $poolStatus]);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主变更新奖池缓存
     */
    public function wishWheelDefenderReset($poolId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            try {
                if (empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '更新奖池缓存异常:参数错误';
                    break;
                }
                $poolInfo = $this->DefenderDrawModel->getWishDefenderPoolById($poolId);
                if (empty($poolInfo)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }

                //查看目前池是高级还是低级
                $poolLevel = $poolInfo['pool_level'];

                $poolList = $this->DefenderDrawModel->getWishDefenderPoolConfig($poolId);
                if (empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '更新奖池缓存异常:数据获取失败';
                    break;
                }
                $poolList = array_column($poolList, 'gift_num', 'id');

                if (in_array($poolInfo['pool_type'], [2, 3])) {
                    $this->DefenderDrawModel->makeWishDefenderSelfPoolData($poolLevel,$poolId, $poolList);
                } else {
                    $this->DefenderDrawModel->makeWishDefenderPoolData($poolLevel, $poolId, $poolList);
                }
            } catch (\Exception $e) {
                $code = Hint::ERROR;
                $msg = '更新奖池缓存异常:' . $e->getMessage();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主变保存奖池配置
     */
    public function wishDefenderSavePoolConfig($poolId, $poolList)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($poolId) || empty($poolList)) {
                break;
            }
            $poolInfo = $this->DefenderDrawModel->getWishDefenderPoolById($poolId);
            if (empty($poolInfo)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //奖池需关闭才可改
            if ($poolInfo['status'] != 2) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池未关闭';
                break;
            }
            $poolMap = $this->DefenderDrawModel->getWishDefenderPoolConfig($poolId);
            if (empty($poolMap)) {
                $code = Hint::PARAM_ERROR;
                $msg = '获取奖池配置失败';
                break;
            }
            $poolMap = array_column($poolMap, null, 'id');
            //过滤
            $flag = 0;
            foreach ($poolList as $val) {
                if (empty($val['gift_id'])) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '奖池配置礼物ID不可为空';
                    $flag = 1;
                    break;
                }
                if (empty($poolMap[$val['id']])) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '奖池配置ID错误';
                    $flag = 1;
                    break;
                }
            }
            if ($flag == 1) {
                break;
            }

            //更新
            DB::beginTransaction();
            try {
                foreach ($poolList as $val) {
                    $id = $val['id'];
                    $giftId = $val['gift_id'];
                    $giftNum = $val['gift_num'];
                    $res = $this->DefenderDrawModel->editWishDefenderPoolConfig($poolId, $id, $giftId, $giftNum);
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_wishDefender', 'error 保存错误', ['msg' => $e->getMessage()]);
                $code = Hint::ERROR;
                $msg = '更新系统异常';
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主变新增奖池
     */
    public function wishDefenderAddPool($poolName, $minNum, $maxNum, $poolType, $ifDefault, $poolLevel)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($poolName)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            if (in_array($poolType, [1]) && (empty($minNum) || empty($maxNum)) || empty($poolLevel)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //个人池 默认只能有一个
            if (in_array($poolType, [2, 3])) {
                if ($ifDefault == 1) {
                    $defaultPool = $this->DefenderDrawModel->getWishDefenderPoolByDefault($poolType, $poolLevel);
                    if (!empty($defaultPool)) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '个人池 默认只能有一个';
                        break;
                    }
                }
                $minNum = $maxNum = 0;
            }

            //新增
            DB::beginTransaction();
            try {
                $poolId = $this->DefenderDrawModel->addWishDefenderPool($poolName, $minNum, $maxNum, $poolType, $ifDefault, $poolLevel);
                if (empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '新增奖池失败';
                    DB::rollBack();
                    break;
                }
                $flag = 0;
                for ($i = 1; $i <= 12; $i++) {
                    $pcId = $this->DefenderDrawModel->addWishDefenderPoolConfig($poolId, $i);
                    if (empty($poolId)) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '新增奖池配置失败';
                        $flag = 1;
                        break;
                    }
                }
                if ($flag == 1) {
                    DB::rollBack();
                    break;
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $code = Hint::ERROR;
                $msg = '新增系统异常';
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主变编辑奖池
     */
    public function wishDefenderEditPool($poolId, $poolName, $minNum, $maxNum, $ifDefault, $pool_level)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($poolId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $poolInfo = $this->DefenderDrawModel->getWishDefenderPoolById($poolId);
            if (empty($poolInfo)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //奖池需关闭才可改
            if ($poolInfo['status'] != 2) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池未关闭';
                break;
            }
            //个人池 默认只能有一个
            if (in_array($poolInfo['pool_type'], [2, 3])) {
                if ($ifDefault == 1) {
                    $defaultPool = $this->DefenderDrawModel->getWishDefenderPoolByDefault($poolInfo['pool_type'], $pool_level);
                    if (!empty($defaultPool) && $defaultPool['id'] != $poolId) {
                        $code = Hint::PARAM_ERROR;
                        $msg = '个人池 默认只能有一个';
                        break;
                    }
                }
                $minNum = $maxNum = 0;
            }

            //更新
            $this->DefenderDrawModel->editWishDefenderPool($poolId, ['pool_name' => $poolName, 'min_num' => $minNum, 'max_num' => $maxNum, 'if_default' => $ifDefault, 'pool_level'=>$pool_level, 'set_defender_num'=>$set_defender_num]);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主变更新奖池缓存
     */
    public function wishDefenderPoolReset($poolId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            try {
                if (empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '更新奖池缓存异常:参数错误';
                    break;
                }
                $poolInfo = $this->DefenderDrawModel->getWishDefenderPoolById($poolId);
                if (empty($poolInfo)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }
                //奖池级别
                $poolLevel = $poolInfo['pool_level'];
                $poolList = $this->DefenderDrawModel->getWishDefenderPoolConfig($poolId);
                if (empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '更新奖池缓存异常:数据获取失败';
                    break;
                }
                $poolList = array_column($poolList, 'gift_num', 'id');

                if (in_array($poolInfo['pool_type'], [2, 3])) {
                    $this->DefenderDrawModel->makeWishDefenderSelfPoolData($poolLevel, $poolId, $poolList);
                } else {
                    $this->DefenderDrawModel->makeWishDefenderPoolData($poolLevel, $poolId, $poolList);
                }
            } catch (\Exception $e) {
                $code = Hint::ERROR;
                $msg = '更新奖池缓存异常:' . $e->getMessage();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主变配置剩余数量
     */
    public function wishDefenderPoolConfigNum($poolId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            try {
                if (empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }
                $poolList = $this->DefenderDrawModel->getWishDefenderPoolConfig($poolId);
                if (empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }
                //获取奖池信息
                $poolInfo = $this->DefenderDrawModel->getWishDefenderPoolById($poolId);
                $hasList = $this->DefenderDrawModel->getWishDefenderPoolData($poolId, $poolInfo['pool_level']);
                $hasList = array_column($hasList, 'num', 'id');

                $giftIds = array_column($poolList, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach ($poolList as $key => $val) {
                    $val['gift_name'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];
                    $val['gift_price'] = empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price'];
                    $val['less_num'] = empty($hasList[$val['id']]) ? 0 : $hasList[$val['id']];
                    $val['draw_num'] = $val['gift_num'] - $val['less_num'];

                    $poolList[$key] = $val;
                }
                $data = $poolList;
            } catch (\Exception $e) {
                $code = Hint::ERROR;
                $msg = '异常:' . $e->getMessage();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主变新增白名单
     */
    public function wishDefenderAddWhite($level, $userId, $giftId, $adminId = 0)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($userId) || empty($giftId) || empty($adminId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //新增
            $whiteId = $this->DefenderDrawModel->addWishDefenderWhite($level, $userId, $giftId, $adminId);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主变删除白名单
     */
    public function wishDefenderDelWhite($whiteId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($whiteId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $res = $this->DefenderDrawModel->delWishDefenderWhite($whiteId);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主取消投放奖池白名单
     */
    public function wishDefenderCancelWhite($whiteId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($whiteId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $res = $this->DefenderDrawModel->cancelWishDefenderWhite($whiteId);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 新增擂主变展示礼物
     */
    public function wishDefenderAddGift($poolLevel, $giftId, $sort)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($giftId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //新增
            $whiteId = $this->DefenderDrawModel->wishDefenderAddGift($poolLevel, $giftId, $sort);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主变删除展示礼物
     */
    public function wishDefenderDelGift($id)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($id)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $res = $this->DefenderDrawModel->wishDefenderDelGift($id);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 新增擂主变赠送展示礼物
     */
    public function wishDefenderSendAddGift($poolLevel, $giftId, $sort)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($giftId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //新增
            $whiteId = $this->DefenderDrawModel->wishDefenderSendAddGift($poolLevel, $giftId, $sort);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主变删除赠送展示礼物
     */
    public function wishDefenderSendDelGift($id)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($id)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $res = $this->DefenderDrawModel->wishDefenderSendDelGift($id);
        } while (false);

        return compact('code', 'msg', 'data');
    }
    /**
     * 擂主变新增个人池用户
     */
    public function wishDefenderAddPoolUser($userId, $poolId, $outDiamondNum, $adminId = 0)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($userId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //判断是否存在
            $poolUserInfo = $this->DefenderDrawModel->getWishDefenderPoolUser($userId);
            if (!empty($poolUserInfo)) {
                $code = Hint::PARAM_ERROR;
                $msg = '用户已存在,不可重复添加';
                break;
            }
            //获取擂主变奖池根据ID
            $poolInfo = $this->DefenderDrawModel->getWishDefenderPoolById($poolId);
            if (empty($poolInfo) || $poolInfo['status'] != 1 || !in_array($poolInfo['pool_type'], [2, 3])) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池不存在或未开启或不是个人池';
                break;
            }
            if ($poolInfo['pool_type'] == 2 && $outDiamondNum > 0) {
                $code = Hint::PARAM_ERROR;
                $msg = '亏损池移除钻石数必须是负数';
                break;
            }
            if ($poolInfo['pool_type'] == 3 && $outDiamondNum < 0) {
                $code = Hint::PARAM_ERROR;
                $msg = '盈利池移除钻石数必须是正数';
                break;
            }

            //初始化擂主变个人奖池配置数据缓存指定用户
            $poolConfigMap = $this->DefenderDrawModel->getWishDefenderPoolConfig($poolId);
            if (empty($poolConfigMap)) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池配置获取失败';
                break;
            }
            $poolConfigMap = array_column($poolConfigMap, 'gift_num', 'id');
            $this->DefenderDrawModel->makeWishWheelSelfPoolDataByPoolIdUserId($poolId, $userId, $poolConfigMap);

            //新增
            $whiteId = $this->DefenderDrawModel->addWishDefenderPoolUser($userId, $adminId, $poolId, $outDiamondNum);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主变删除个人池用户
     */
    public function wishDefenderDelPoolUser($id, $adminId = 0)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($id)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //判断是否存在
            $poolUserInfo = $this->DefenderDrawModel->getWishDefenderPoolUserById($id);
            if (empty($poolUserInfo) || $poolUserInfo['is_delete'] == 1) {
                break;
            }

            $res = $this->DefenderDrawModel->wishDefenderDelPoolUser($id, $poolUserInfo['user_id'], $adminId);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    //查看个人奖池配置剩余数量
    public function wishDefenderPoolSelfConfigNum($poolId, $userId)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            try {
                if (empty($poolId)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }
                $poolInfo = $this->DefenderDrawModel->getWishDefenderPoolById($poolId);
                if (empty($poolInfo)) {
                    $code = Hint::PARAM_ERROR;
                    break;
                }
                if (!in_array($poolInfo['pool_type'], [2, 3])) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '不是个人奖池';
                    break;
                }

                //用户是否在
                $poolUserInfo = $this->DefenderDrawModel->getWishDefenderPoolUser($userId);
                if (empty($poolUserInfo) || $poolUserInfo['pool_id'] != $poolId) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '用户不在此个人池中';
                    break;
                }

                $poolList = $this->DefenderDrawModel->getWishDefenderPoolConfig($poolId);
                if (empty($poolList)) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '更新奖池缓存异常:数据获取失败';
                    break;
                }

                $hasList = $this->DefenderDrawModel->getWishDefenderSelfPoolData($poolId, $userId);
                $hasList = array_column($hasList, 'num', 'id');

                $giftIds = array_column($poolList, 'gift_id');
                $giftList = $this->giftModel->getGiftByGiftIds($giftIds, ['gift_id', 'name', 'price']);
                $giftList = array_column($giftList, null, 'gift_id');

                foreach ($poolList as $key => $val) {
                    $val['gift_name'] = empty($giftList[$val['gift_id']]['name']) ? '' : $giftList[$val['gift_id']]['name'];
                    $val['gift_price'] = empty($giftList[$val['gift_id']]['price']) ? 0 : $giftList[$val['gift_id']]['price'];
                    $val['less_num'] = empty($hasList[$val['id']]) ? 0 : $hasList[$val['id']];
                    $val['draw_num'] = $val['gift_num'] - $val['less_num'];

                    $poolList[$key] = $val;
                }
                $data = $poolList;
            } catch (\Exception $e) {
                $code = Hint::ERROR;
                $msg = '异常:' . $e->getMessage();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主变新增奖池白名单
     */
    public function wishDefenderAddPoolWhite($userId, $giftId, $adminId = 0, $pool_level)
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($userId) || empty($giftId) || empty($adminId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //个人池用户
            $poolUser = $this->DefenderDrawModel->getWishDefenderPoolUserId($userId, $pool_level);
            if (!empty($poolUser)) {
                $code = Hint::PARAM_ERROR;
                $msg = '用户在个人池 不可添加奖池白名单';
                break;
            }

            //获取用户当前抽奖的奖池
            //奖池
            $pool = $this->DefenderDrawModel->getWishDefenderPool($pool_level);
            $basePoolList = []; //普通池的
            $userPoolList = []; //用户个人池的
            foreach ($pool as $val) {
                if ($val['status'] != 1) {
                    continue;
                }
                //奖池配置数据
                $poolConfig = $this->DefenderDrawModel->getWishDefenderPoolConfig($val['id']);
                if (empty($poolConfig)) {
                    continue;
                }
                $val['poolConfig'] = $poolConfig;
                //普通池
                if ($val['pool_type'] == 1) {
                    $basePoolList[] = $val;
                }
            }
            $poolList = []; //已开启的奖池
            if (empty($poolUser)) {
                $poolList = $basePoolList;
            }
            if (empty($poolList)) {
                $code = Hint::WAIT_OPEN;
                $msg = '创建失败，当前没有已开启的奖池';
                break;
            }

            //用户总抽奖记录数
            $drawNumNow = $drawNum = $this->DefenderDrawModel->getUserWishDefenderDrawNumByWeek($userId, $pool_level);
            $drawNumNow = $drawNumNow + 1;

            $usePool = []; //使用的奖池
            //在范围的
            foreach ($poolList as $val) {
                if ($val['min_num'] <= $drawNumNow && $drawNumNow <= $val['max_num']) {
                    $usePool = $val;
                }
            }
            //上一个
            $prevNum = 0;
            if (empty($usePool)) {
                foreach ($poolList as $val) {
                    if ($val['max_num'] <= $drawNumNow && $prevNum <= $val['max_num']) {
                        $usePool = $val;
                        $prevNum = $val['max_num'];
                    }
                }
            }
            //下一个
            $nextNum = 0;
            if (empty($usePool)) {
                foreach ($poolList as $val) {
                    if ($val['min_num'] >= $drawNumNow && ($nextNum == 0 || $nextNum >= $val['min_num'])) {
                        $usePool = $val;
                        $nextNum = $val['min_num'];
                    }
                }
            }
            //还是没有取第一个
            if (empty($usePool)) {
                $usePool = $poolList[0];
            }
            $poolId = $usePool['id'];

            $poolConfigId = 0;
            foreach ($usePool['poolConfig'] as $val) {
                if ($val['gift_id'] == $giftId) {
                    $poolConfigId = $val['id'];
                }
            }
            if (empty($poolConfigId)) {
                $code = Hint::WAIT_OPEN;
                $msg = '创建失败，用户将抽取奖池配置中无此礼物';
                break;
            }

            //自指定奖池中抽取指定的余量
            if (in_array($usePool['pool_type'], [2, 3])) {
                //个人池
                $res = $this->DefenderDrawModel->drawWishDefenderAppoint($pool_level,$usePool['id'], $poolConfigId, $userId);
            } else {
                //普通
                $res = $this->DefenderDrawModel->drawWishDefenderAppoint($pool_level, $usePool['id'], $poolConfigId, 0);
            }
            if ($res) {
                //新增
                $whiteId = $this->DefenderDrawModel->addWishDefenderWhite($pool_level,$userId, $giftId, $adminId, $poolId);
                if (!$whiteId) {
                    $code = Hint::WAIT_OPEN;
                    $msg = '创建失败，奖池余量扣除成功,数据写入失败';
                    break;
                }
            } else {
                $code = Hint::WAIT_OPEN;
                $msg = '创建失败，奖池无余量';
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主变奖池更新阀值
     */
    public function wishDefenderSetUserPoolConfig($poolId, $upData = [])
    {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (empty($poolId)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            $poolInfo = $this->DefenderDrawModel->getWishDefenderPoolById($poolId);
            if (empty($poolInfo)) {
                $code = Hint::PARAM_ERROR;
                break;
            }
            //奖池需关闭才可改
            if (!in_array($poolInfo['pool_type'], [2, 3])) {
                $code = Hint::PARAM_ERROR;
                $msg = '奖池不是个人池';
                break;
            }

            //亏损池
            if ($poolInfo['pool_type'] == 2) {
                if (!empty($params['in_profit_loss']) && $params['in_profit_loss'] < 0) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '亏损池进入钻石数必须大于0';
                    break;
                }
                if (!empty($params['in_profit_rate']) && $params['in_profit_loss'] < 100) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '亏损池进入返奖率必须大于100%';
                    break;
                }
            }

            //盈利池
            if ($poolInfo['pool_type'] == 3) {
                if (!empty($params['in_profit_loss']) && $params['in_profit_loss'] > 0) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '盈利池进入钻石数必须小于0';
                    break;
                }
                if (!empty($params['in_profit_rate']) && $params['in_profit_loss'] > 100) {
                    $code = Hint::PARAM_ERROR;
                    $msg = '盈利池进入返奖率必须小于100%';
                    break;
                }
            }
            if (!empty($params['out_profit_rate']) && $params['out_profit_rate'] < 0) {
                $code = Hint::PARAM_ERROR;
                $msg = '个人池移除钻石比例必须大于0';
                break;
            }

            //更新
            $this->DefenderDrawModel->editWishDefenderPool($poolId, $upData);
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 擂主变每日统计
     */
    public function statisticalData($ymd, $poolLevel)
    {
        do {
            $dateSt = date('Y-m-d 00:00:00', strtotime($ymd));
            $dateEt = date('Y-m-d 23:59:59', strtotime($ymd));
            $info = $this->DefenderDrawModel->wishPoolStatistics($dateSt, $dateEt, $poolLevel);

            $data = [];
            $data['ymd'] = date('Ymd', strtotime($ymd));
            $data['user_num'] = empty($info['user_num']) ? 0 : $info['user_num'];
            $data['draw_num'] = empty($info['draw_num']) ? 0 : $info['draw_num'];
            $data['prop_num'] = empty($info['prop_num']) ? 0 : $info['prop_num'];
            $data['prop_diamond_num'] = empty($info['prop_diamond_num']) ? 0 : $info['prop_diamond_num'];
            $data['reward_diamond_num'] = empty($info['reward_diamond_num']) ? 0 : $info['reward_diamond_num'];
            $data['pool_level'] = $poolLevel;
            $data['profit_loss'] = $data['prop_diamond_num'] - $data['reward_diamond_num'];

            $this->DefenderDrawModel->addWishPoolStatistics($data);
        } while (false);

        return $data;
    }

    //获取擂主变恋爱卡价格
    public function getUniversePrice(){
        $DefenderDrawInfo = $this->DefenderDrawModel->DefenderDrawInfo(1000);
        $DefenderDrawPrice = empty($DefenderDrawInfo['price']) ? 0 : $DefenderDrawInfo['price'];
        return $DefenderDrawPrice;
    }

    //获取全服进度信息
    public function getProgess(){
        $config = $this->DefenderDrawModel->getWishPoolConfig();
        //进度
        $allStart = Redis::get($this->allUniverseValue);
        $allStart = empty($allStart) ? 0 : $allStart;
        $allStart = number_format(($allStart/$config['changePoolLimit']) * 100, 2, '.', '');
        //获取当前抽奖id
        $DefenderId = Redis::get($this->universeDefenderId);
        $DefenderId = empty($DefenderId) ? 1000 : $DefenderId;
        $DefenderEndTime = Redis::get($this->universeEndTime);
        $diffMinutes = 0;
        if(!empty($DefenderEndTime)){
            $DefenderEndTime = strtotime(date('Y-m-d H:i',strtotime($DefenderEndTime)));
            $now = strtotime(date('Y-m-d H:i',time()));
            $diffMinutes = ($DefenderEndTime - $now)/60;
        }
        $return = [
            'Defender_id' => $DefenderId,
            'leaveMinutes' => $diffMinutes,
            'progress' => $allStart,
            'openLimit' => $config['changePoolLimit'],
        ];
        return $return;
    }

    //获取擂主值排行榜
    public function getUniverseRank($type, $userId){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do{
            if(empty($type) || empty($userId)){
                $code = Hint::PARAM_ERROR;
                break;
            }
            $finalArray = [];
            //日榜
            if($type == 1){
                $todayStart = Carbon::today()->startOfDay()->toDateString();
                $dayKey = $this->dayStarRank.$todayStart;
                $allSort = Redis::zrevrangebyscore($dayKey,'+inf','-inf',['withscores'=>true , 'limit'=>[0,10]]);
                if(!empty($allSort)){
                    $finalArray = $allSort;
                }
                //我当前所在的等级
                $myLevel = $this->myLevel($dayKey, $userId);

                $awardInfo = build_image($this->dayAwardPic);
                $returnData = $this->getInfoByArray($finalArray, $dayKey);
            }elseif($type == 2){
                $weekStart = Carbon::today()->startOfWeek()->toDateString();
                $weekEnd = Carbon::today()->endOfWeek()->toDateString();
                $weekKey = $this->weekStarRank.$weekStart.'-'.$weekEnd;
                $allSort = Redis::zrevrangebyscore($weekKey,'+inf','-inf',['withscores'=>true , 'limit'=>[0,10]]);
                if(!empty($allSort)){
                    $finalArray = $allSort;
                }
                //我当前所在的等级
                $myLevel = $this->myLevel($weekKey, $userId);
                $awardInfo = build_image($this->weekAwardPic);
                $returnData = $this->getInfoByArray($finalArray, $weekKey);
            }
            $data = [
                'award' => $awardInfo,
                'rankList' => empty($returnData) ? [] : $returnData,
                'myLevel' => $myLevel,
            ];
        }while(false);
        return compact('code','data','msg');
    }

    //整理信息
    public function getInfoByArray($finalArray, $redisKey){
        $page = 1;
        $limit = 10;
        foreach($finalArray as $k=>$v)
        {
            $userInfo = $this->userModel->get_user($k);
            $userInfo['images'] = $userInfo['images'][0];

            $returnData[$k]['userId'] = $k;
            $returnData[$k]['nickname'] = $userInfo['nickname'];
            $returnData[$k]['uuid'] = $userInfo['user_uid'];
            $returnData[$k]['avatar'] = $userInfo['images'];
            $returnData[$k]['points'] = $v;
            $diffInfo = $this->myLevel($redisKey, $k);
            $returnData[$k]['diff_points'] = $diffInfo['diff_points'];
        }
        $returnData = array_values($returnData);
        //排名更新
        foreach($returnData as $k =>$val)
        {
            $returnData[$k]['rank'] = $page ? ($page * $limit - $limit + $k + 1) : $k;
            if($returnData[$k]['rank'] == 1){
                $returnData[$k]['diff_points'] = '';
            }
        }
        return $returnData;
    }

    //我所在的楼层
    public function myLevel($redisKey, $user_id){
        $myLevelScore = 0;
        $nowlevel = Redis::ZREVRANK($redisKey,$user_id);
        //我目前值
        $myLevelScore = Redis::ZSCORE($redisKey,$user_id);

        $sortLevel = Redis::zrevrange($redisKey,0,10);
        $lastKey = end($sortLevel);
        $diffLevel = Redis::ZSCORE($redisKey,$lastKey); //相差礼物数
        if(isset($sortLevel[$nowlevel-1]) && $nowlevel <= 10){
            $upLevel = $sortLevel[$nowlevel-1];
            //查询对应socre值
            $upLevelScore = Redis::ZSCORE($redisKey,$upLevel);
            //我目前值
            $myLevelScore = Redis::ZSCORE($redisKey,$user_id);
            //相差送礼数量
            $diffLevel = $upLevelScore - $myLevelScore;
        }
        if(is_null($nowlevel)){
            $level = '未上榜'; //目前排名
        }elseif($nowlevel == 0){
            $level = 1; //目前排名
        }elseif($nowlevel > 10){
            $level = '未上榜'; //目前排名
        }else{
            $level = $nowlevel+1;//默认第一名从0开始要加1后面的
        }
        $userInfo = $this->userModel->get_user($user_id);
        $userInfo['images'] = $userInfo['images'][0];
        $myLevelScore = empty($myLevelScore) ? 0 : $myLevelScore;
        $myLevelScore = number_format($myLevelScore/100,2,'.','');
        if($myLevelScore >= 10000){
            $myLevelScore = number_format($myLevelScore/10000, 2, '.', '');
            $myLevelScore = $myLevelScore.'w';
        }
        $diffLevel =  number_format($diffLevel/100,2,'.','');
        if($diffLevel >=10000){
            $diffLevel =  number_format($diffLevel/10000, 2, '.', '');
            $diffLevel = $diffLevel.'w';
        }
        $finaData = [
            'userId' => empty($userInfo['user_id']) ? 0 : $userInfo['user_id'],
            'nickname' => empty($userInfo['nickname']) ? '用户'.$userInfo['user_uid'] : $userInfo['nickname'],
            'uuid' => empty($userInfo['user_uid']) ? 0 : $userInfo['user_uid'],
            'avatar' =>  empty($userInfo['images']) ? '' : $userInfo['images'],
            'points' => $myLevelScore,
            'rank' => $level,
            'diff_points' => empty($diffLevel) ? 0 : $diffLevel,
        ];
        return $finaData;
    }

    //发放奖励信息
    public function sendAward($type){
        if($type == 1 ){
            $goodsInfo = $this->mall_model->getMallGoodByGoodsId(169);
            $popGoodsInfo = $this->mall_model->getMallGoodByGoodsId(170);
            $awardInfo = [
                'first' => [
                    'goods_id' => $goodsInfo['goods_id'],
                    'goods_type' => $goodsInfo['goods_type'],
                    'name' => $goodsInfo['goods_name'],
                    'day' => 1,
                    'image' => build_image($goodsInfo['big_img']),
                    'pop_goods_id' => $popGoodsInfo['goods_id'],
                    'pop_name' => $popGoodsInfo['goods_name'],
                    'pop_goods_type' => $popGoodsInfo['goods_type'],
                    'seat_goods_id' => 0,
                ],
                'second' => [],
                'third' => []
            ];
        }elseif($type == 2 ){
            $goodsInfo = $this->mall_model->getMallGoodByGoodsId(169);
            $popGoodsInfo = $this->mall_model->getMallGoodByGoodsId(170);
            $seatGoodsInfo = $this->mall_model->getMallGoodByGoodsId(171);
            $sencodeInfo = $this->mall_model->getMallGoodByGoodsId(169);
            $thirdInfo = $this->mall_model->getMallGoodByGoodsId(169);
            $awardInfo = [
                'first' => [
                    'goods_id' => $goodsInfo['goods_id'],
                    'goods_type' => $goodsInfo['goods_type'],
                    'name' => $goodsInfo['goods_name'],
                    'day' => 7,
                    'image' => build_image($goodsInfo['big_img']),
                    'pop_goods_id' => $popGoodsInfo['goods_id'],
                    'pop_name' => $popGoodsInfo['goods_name'],
                    'pop_goods_type' => $popGoodsInfo['goods_type'],
                    'seat_goods_id' => $seatGoodsInfo['goods_id'],
                    'seat_name' => $seatGoodsInfo['goods_name'],
                    'seat_goods_type' => $seatGoodsInfo['goods_type'],
                ],
                'second' => [
                    'goods_id' => $sencodeInfo['goods_id'],
                    'goods_type' => $sencodeInfo['goods_type'],
                    'name' => $sencodeInfo['goods_name'],
                    'day' => 7,
                    'image' => build_image($sencodeInfo['big_img']),
                    'pop_goods_id' => $popGoodsInfo['goods_id'],
                    'pop_name' => $popGoodsInfo['goods_name'],
                    'pop_goods_type' => $popGoodsInfo['goods_type'],
                    'seat_goods_id' => $seatGoodsInfo['goods_id'],
                    'seat_name' => $seatGoodsInfo['goods_name'],
                    'seat_goods_type' => $seatGoodsInfo['goods_type'],
                ],
                'third' => [
                    'goods_id' => $thirdInfo['goods_id'],
                    'goods_type' => $thirdInfo['goods_type'],
                    'name' => $thirdInfo['goods_name'],
                    'day' => 7,
                    'image' => build_image($thirdInfo['big_img']),
                    'pop_goods_id' => $popGoodsInfo['goods_id'],
                    'pop_name' => $popGoodsInfo['goods_name'],
                    'pop_goods_type' => $popGoodsInfo['goods_type'],
                    'seat_goods_id' => $seatGoodsInfo['goods_id'],
                    'seat_name' => $seatGoodsInfo['goods_name'],
                    'seat_goods_type' => $seatGoodsInfo['goods_type'],
                ]
            ];
        }
        return $awardInfo;
    }

    //发放每日奖励
    public function sendYestordayAward($yestorday){
        $key = $this->dayStarRank.$yestorday;
        $allSort = Redis::zrevrangebyscore($key,'+inf','-inf',['withscores'=>true , 'limit'=>[0,10]]);
        $allSort = array_keys($allSort);
        //发放第一名奖励
        $sendAward = $this->sendAward(1);
        $res = $this->sendAwardHandle($sendAward,'first',$allSort[0],1);
        return $res;
    }

    //发放每周奖励
    public function sendWeekAward($startWeek, $endWeek){
        $weekKey = $this->weekStarRank.$startWeek.'-'.$endWeek;
        $allSort = Redis::zrevrangebyscore($weekKey,'+inf','-inf',['withscores'=>true , 'limit'=>[0,10]]);
        $allSort = array_keys($allSort);
        $sendAward = $this->sendAward(2);
        foreach($allSort as $k=>$v){
            //发放第一名奖励
            if($k == 0){
                $this->sendAwardHandle($sendAward,'first',$v,2);
            }elseif($k == 1){
                $this->sendAwardHandle($sendAward,'second',$v,2);
            }elseif($k == 2){
                $this->sendAwardHandle($sendAward,'third',$v,2);
            }else{
                break;
            }
        }
    }

    //周榜日榜发放奖励
    public function sendAwardHandle($sendAward,$keyName='first', $userId, $type=1){
        //有效期
        $timeLimit = $sendAward[$keyName]['day'] * 86400;
        //头像
        $skuList = $this->mall_model->getSkuDataByGoods($sendAward[$keyName]['goods_id']);
        //气泡
        $popSkuList = $this->mall_model->getSkuDataByGoods($sendAward[$keyName]['pop_goods_id']);
        //进场
        $seatSkuList = [];
        if(!empty($sendAward[$keyName]['seat_goods_id'])){
            $seatSkuList = $this->mall_model->getSkuDataByGoods($sendAward[$keyName]['seat_goods_id']);
        }
        //商品增加
        $res = $this->mall_model->shoppingAct(
            11,
            $userId,
            $sendAward[$keyName]['goods_id'],
            $sendAward[$keyName]['name'],
            $sendAward[$keyName]['goods_type'],
            $skuList[0]['sku_id'],
            $timeLimit,
            0,
            $timeLimit,
            time(),
            2
        );
        //入库记录
        $data = [
            'user_id' =>  $userId,
            'goods_id' => $sendAward[$keyName]['goods_id'],
            'goods_name' => $sendAward[$keyName]['name'],
            'day' => $sendAward[$keyName]['day'],
            'type' => $type,
            'send_time' => date('Y-m-d H:i:s',time()),
            'created_at' => date('Y-m-d H:i:s',time()),
        ];
        $this->DefenderDrawModel->insertSendAwardLog($data);

        //气泡增加
        $res = $this->mall_model->shoppingAct(
            11,
            $userId,
            $sendAward[$keyName]['pop_goods_id'],
            $sendAward[$keyName]['pop_name'],
            $sendAward[$keyName]['pop_goods_type'],
            $popSkuList[0]['sku_id'],
            $timeLimit,
            0,
            $timeLimit,
            time(),
            2
        );
        //入库记录
        $data = [
            'user_id' =>  $userId,
            'goods_id' => $sendAward[$keyName]['pop_goods_id'],
            'goods_name' => $sendAward[$keyName]['pop_name'],
            'day' => $sendAward[$keyName]['day'],
            'type' => $type,
            'send_time' => date('Y-m-d H:i:s',time()),
            'created_at' => date('Y-m-d H:i:s',time()),
        ];
        $this->DefenderDrawModel->insertSendAwardLog($data);
        //进场
        if(!empty($seatSkuList)){
            $res = $this->mall_model->shoppingAct(
                11,
                $userId,
                $sendAward[$keyName]['seat_goods_id'],
                $sendAward[$keyName]['seat_name'],
                $sendAward[$keyName]['seat_goods_type'],
                $seatSkuList[0]['sku_id'],
                $timeLimit,
                0,
                $timeLimit,
                time(),
                2
            );
            //入库记录
            $data = [
                'user_id' =>  $userId,
                'goods_id' => $sendAward[$keyName]['seat_goods_id'],
                'goods_name' => $sendAward[$keyName]['seat_name'],
                'day' => $sendAward[$keyName]['day'],
                'type' => $type,
                'send_time' => date('Y-m-d H:i:s',time()),
                'created_at' => date('Y-m-d H:i:s',time()),
            ];
            $this->DefenderDrawModel->insertSendAwardLog($data);
        }
        return $res;
    }

    //触发高级池公告(房间公告,飘屏公告)
    public function sendOpenPoolMsg($roomId=0){
        $endTime = Redis::get($this->universeEndTime);
        $endTimeToMinutes = date('Y-m-d H:i',strtotime($endTime));
        $diffMinutes = Carbon::now()->diffInMinutes($endTimeToMinutes);

        //所有房间信息
        $list = $this->roomHotModel->getAllRoomHotIdData();
        $list = json_decode($list, true);
        //飘屏公告
        $this->msgService->sendFullScreen(70, null, ['minutes' =>$diffMinutes,'giftPrice'=>0], []);
        //房间公告
        foreach($list as $val) {
            if(isset($val['b']) && $val['b']==1) {
                $this->msgService->roomOpenPoolMsg($val['r'], ['minutes'=>$diffMinutes,'text_content'=>'双倍']);
            }
        }

    }

    //每分钟检查是否要切换奖池
    public function changePool(){
        $DefenderId = Redis::get($this->universeDefenderId);
        if($DefenderId == 1001){
            $endTime = Redis::get($this->universeEndTime);
            $endTimeToMinutes = date('Y-m-d H:i',strtotime($endTime));
            $now = date('Y-m-d H:i',time());
            if($now >= $endTimeToMinutes){
                //切换奖池
                Redis::set($this->universeDefenderId,1000);
                Redis::set($this->universeEndTime,0);
                //获取目前全服擂主值
                $nowStarValue = Redis::get($this->allUniverseValue);
                $config = $this->DefenderDrawModel->getWishPoolConfig();
                $setNewStartValue = $nowStarValue - $config['changePoolLimit'];
                //若差值大于本次设置的阀值继续高级池
                if($setNewStartValue >= $config['changePoolLimit']){
                    Redis::set($this->universeDefenderId,1001);
                    $now = Carbon::now()->timestamp;
                    $now = date('Y-m-d H:i',$now);

                    $endTime = strtotime($now) + $config['openMinutes'] * 60;
                    Redis::set($this->universeEndTime,date('Y-m-d H:i:s',$endTime));
                    //飘屏公告
                    $this->sendOpenPoolMsg();
                }
                if($setNewStartValue < 0){
                    $setNewStartValue = 0;
                }
                Redis::set($this->allUniverseValue,$setNewStartValue);
                $progressInfo = $this->getProgess();
                $this->msgService->sendUniverse([], $progressInfo['progress'], $progressInfo['Defender_id'], $progressInfo['leaveMinutes']);
                return 1;
            }else{
                $progressInfo = $this->getProgess();
                $this->msgService->sendUniverse([], $progressInfo['progress'], $progressInfo['Defender_id'], $progressInfo['leaveMinutes']);
                return 1;
            }
        }
        return 0;
    }
}
